using UnityEngine;
using QFramework;
using System.Linq;

// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间
// 2.命名空间更改后，生成代码之后，需要把逻辑代码文件（非 Designer）的命名空间手动更改
namespace QFramework.Example
{
	public partial class SimpleKnife : ViewController
	{

		private float float_CreatTimer;
		void Start()
		{
			// Code Here
		}

		void Update()
		{
			float_CreatTimer += Time.deltaTime;

			if (float_CreatTimer >= 1f)
			{
				if (Player.Default)
				{


					var enemys = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

					var enemy = enemys.OrderBy(item => (Player.Default.transform.position - item.transform.position).magnitude).FirstOrDefault();

					MiniMenemy miniM = null;

					if (!enemy)
					{
						miniM = FindObjectOfType<MiniMenemy>();
						if (!miniM)
						{
							return;
						}
					}

					Knife.Instantiate().Show()
					.Position(this.Position())
					.Self((self) =>
					{
						self.OnTriggerEnter2DEvent((collection) =>
						{
							if (collection.GetComponent<HurttBox>())
							{
								if (collection == null || collection.GetComponent<HurttBox>() == null || collection.GetComponent<HurttBox>().owner == null) return;
								if (collection.GetComponent<HurttBox>().owner.CompareTag("Enemy"))
								{
									collection.GetComponent<HurttBox>().owner.GetComponent<IEnemy>().OnSetHp(-5f);
									self.DestroyGameObjGracefully();
								}
							}
						}).UnRegisterWhenGameObjectDestroyed(self);
						Vector2 enemyPos = Vector2.zero;
						if (enemy != null)
						{
							enemyPos = enemy.NormalizedDirection2DFrom(Player.Default);
						}
						else if (miniM != null)
						{
							enemyPos = miniM.NormalizedDirection2DFrom(Player.Default);
						}
						self.transform.up = enemyPos;

						self.GetComponent<Rigidbody2D>().velocity = enemyPos * 10;

						ActionKit.OnUpdate.Register(() =>
						{
							if (Player.Default)
							{
								float dis = (Player.Default.Position() - self.Position()).magnitude;

								if (dis >= 15f)
								{
									self.DestroyGameObjGracefully();
								}
							}

						}).UnRegisterWhenGameObjectDestroyed(self);
					});

				}

				float_CreatTimer = 0;
			}
		}
	}
}
